package com.kuaidi.zhangke.kuaidi;

import android.Manifest;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.view.SurfaceView;
import android.view.View;

import android.widget.ImageView;
import android.widget.Toast;


import com.google.zxing.Result;
import com.kuaidi.zhangke.kuaidi.zxing.ScanListener;
import com.kuaidi.zhangke.kuaidi.zxing.ScanManager;
import com.kuaidi.zhangke.kuaidi.zxing.decode.Utils;




/**
 * 扫码
 */

public class SweepYardActivity extends AppCompatActivity implements View.OnClickListener,ScanListener {

    SurfaceView scanPreview = null;
    private ImageView sweep_flash;
    View scanContainer;
    View scanCropView;
    private ImageView scanLine;
    private MyImageView scan_image;

    private ScanManager manager;
    private PackageManager packageManager;
    private int scanMode;//扫描模型（条形，二维码，全部）
    final public static int REQUEST_CODE_ASK_CALL_PHONE = 123;
    final int PHOTOREQUESTCODE = 1111;




    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.layout_sweep);

        initFindView();
    }

    public void initFindView() {

        setScanManager();


    }

    private void setScanManager(){
        //打开扫描界面扫描条形码或二维码
        scanMode=getIntent().getIntExtra(Constant.REQUEST_SCAN_MODE,Constant.REQUEST_SCAN_MODE_ALL_MODE);
        packageManager=getPackageManager();
        // 判断版本是6.0的动态获取权限
        if (Build.VERSION.SDK_INT >= 23) {
            int checkCallPhonePermission = ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA);
            if(checkCallPhonePermission != PackageManager.PERMISSION_GRANTED){
                ActivityCompat.requestPermissions(this,new String[]{Manifest.permission.CAMERA},REQUEST_CODE_ASK_CALL_PHONE);
            }
        }
        initView();
        initOnClick();
    }

    private void initView() {
        sweep_flash= (ImageView) findViewById(R.id.sweep_flash);
        scan_image= (MyImageView) findViewById(R.id.scan_image);
        scanPreview = (SurfaceView) findViewById(R.id.capture_preview);
        scanContainer = findViewById(R.id.capture_container);//整体布局
        scanCropView = findViewById(R.id.capture_crop_view);//扫码框
        scanLine = (ImageView) findViewById(R.id.capture_scan_line);//扫码线

        // 按钮


        //构造出扫描管理器
        manager = new ScanManager(SweepYardActivity.this, scanPreview, scanContainer, scanCropView, scanLine, scanMode,this,sweep_flash);
    }


    public void initOnClick() {
        sweep_flash.setOnClickListener(this);
    }

    public void initData() {

    }

    @Override
    public void onClick(View v) {
        int id=v.getId();
        switch (id){

            case R.id.sweep_flash:
                manager.switchLight();
                break;
        }
    }




    @Override
    protected void onDestroy() {
        super.onDestroy();

    }




    @Override
    public void scanError(Exception e) {
//相机扫描出错时
        if(e.getMessage()!=null&&e.getMessage().startsWith("相机")){
            scanPreview.setVisibility(View.INVISIBLE);
        }
    }

    @Override
    public void onResume() {
        super.onResume();

        manager.onResume();
//        scan_image.setVisibility(View.GONE);

    }

    @Override
    public void onPause() {
        super.onPause();
        manager.onPause();
    }


    /**
     * 返回結果
     * @param rawResult  结果对象
     * @param bundle  存放了截图，或者是空的
     */
    public void scanResult(Result rawResult, Bundle bundle) {
        //扫描成功后，扫描器不会再连续扫描，如需连续扫描，调用reScan()方法。

        String code =rawResult.getText();
        //Toast.makeText(SweepYardActivity.this,code,Toast.LENGTH_SHORT).show();
        Intent intent =new Intent(SweepYardActivity.this, FourActivity.class);
        intent.putExtra("code",code);
        startActivity(intent);
        finish();


    }
    public void showPictures(int requestCode) {
        Intent intent = new Intent(Intent.ACTION_PICK);
        intent.setType("image/*");
        startActivityForResult(intent, requestCode);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        String photo_path;
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case PHOTOREQUESTCODE:
                    String[] proj = {MediaStore.Images.Media.DATA};
                    Cursor cursor = this.getContentResolver().query(data.getData(), proj, null, null, null);
                    if (cursor.moveToFirst()) {
                        int colum_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
                        photo_path = cursor.getString(colum_index);
                        if (photo_path == null) {
                            photo_path = Utils.getPath(getApplicationContext(), data.getData());
                        }
                        manager.scanningImage(photo_path);
                    }
            }
        }
    }

    /**
     * 開始掃描
     */
    private void startScan(){
        scan_image.setVisibility(View.GONE);
        manager.reScan();
    }








}
